package com.netwit.shiro.jwt;

import com.alibaba.druid.support.json.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {

    /**
     * 判断用户是否要登录，头信息中是否包含了 Authorization 字段
     */
    private boolean isLoginAttemp(ServletRequest request, ServletResponse response) {
        //String authorization = ((HttpServletRequest) request).getHeader("Authorization");
        String authorization = getToken((HttpServletRequest)request);
        log.info("[isLoginAttemp] " + ((HttpServletRequest) request).getRequestURI() + " token is " + authorization);
        return !StringUtils.isEmpty(authorization);
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        //String authorization = ((HttpServletRequest) request).getHeader("Authorization");
        String authorization = getToken((HttpServletRequest)request);
        JWToken token = new JWToken(authorization);
        // 登录验证
        getSubject(request, response).login(token);
        return true;
    }

    /**
     * 如果带有 Authorization，则对 Authorization 进行检查，否则直接通过
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttemp(request, response)) {
            try{
                executeLogin(request, response);
            } catch (Exception e) {
                response401(request, response);
            }
        }
        //如果请求不存在 Authorization, 则可能是执行登录操作或游客状态访问, 无需检查, 直接返回 true
        return true;
    }

    /**
     * 提供跨域支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse)response;
        HttpServletRequest  req = (HttpServletRequest)request;
        res.setHeader("Access-control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        res.setHeader("Access-control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个 option 请求, 这里直接给返回正常状态
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            res.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 非法请求跳转到 401 或 登录页
     */
    private void response401(ServletRequest request, ServletResponse response) {
        try{
            //((HttpServletResponse) response).sendRedirect(((HttpServletRequest)request).getContextPath() + "/401");
            HttpServletRequest req = (HttpServletRequest)request;
            ((HttpServletResponse) response).sendRedirect(req.getContextPath() + "/login?nexturl=" + req.getRequestURI());
        } catch (IOException ioe) {
            log.error(ioe.getMessage());
        }
    }

    /**
     * 获取 cookie 中的 token
     */
    private String getToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String token = "";
        for (Cookie cookie : cookies) {
            if ("token".equalsIgnoreCase(cookie.getName())) {
                token = cookie.getValue();
                break;
            }
        }
        return token;
    }
}
